package com.apy.accountbook

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.apy.accountbook.model.AppDatabase
import com.apy.accountbook.model.Bill
import kotlinx.coroutines.*

class AddRecordActivity : AppCompatActivity() {

    private lateinit var rvPrimaryCategories: RecyclerView
    private lateinit var vpSecondaryCategories: ViewPager
    private lateinit var etNote: EditText
    private lateinit var etMoney: EditText
    private lateinit var ivNoteIcon: ImageView
    private lateinit var database: AppDatabase

    // 保存选中的二级分类ID
    private var selectedSecondaryCategoryId: Int? = null
        set(value) {
            field = value
            // 当选中值改变时，刷新所有可见的RecyclerView
            for (i in 0 until vpSecondaryCategories.childCount) {
                val child = vpSecondaryCategories.getChildAt(i)
                if (child is RecyclerView) {
                    child.adapter?.notifyDataSetChanged()
                }
            }
        }

    // 分类数据类
    data class CategoryItem(
        val id: Int,
        val name: String
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置窗口属性，使其显示为对话框样式
        window.setLayout(
            resources.getDimensionPixelSize(R.dimen.dialog_width),
            resources.getDimensionPixelSize(R.dimen.dialog_height)
        )

        database = AppDatabase.getDatabase(this)

        showAddRecordDialog()
    }

    private fun showAddRecordDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_record, null)
        rvPrimaryCategories = dialogView.findViewById(R.id.rvPrimaryCategories)
        vpSecondaryCategories = dialogView.findViewById(R.id.vpSecondaryCategories)
        etNote = dialogView.findViewById(R.id.etNote)
        etMoney = dialogView.findViewById(R.id.et_amount)
        ivNoteIcon = dialogView.findViewById(R.id.ivNoteIcon)

        // 设置一级分类假数据
        val primaryCategories = listOf("衣", "食", "住", "行", "娱乐", "健康", "学习", "其他")
        val primaryCategoryAdapter = PrimaryCategoryAdapter(primaryCategories)
        primaryCategoryAdapter.setOnItemClickListener { position ->
            // Handle item click event
        }
        rvPrimaryCategories.adapter = primaryCategoryAdapter

        // 设置二级分类假数据（模拟从服务器获取的数据）
        val allSecondaryCategories = listOf(
            CategoryItem(1, "早餐"), CategoryItem(2, "午餐"),
            CategoryItem(3, "晚餐"), CategoryItem(4, "早餐"),
            CategoryItem(5, "午餐1"), CategoryItem(6, "晚餐1"),
            CategoryItem(7, "玩具"), CategoryItem(8, "加油"),
            CategoryItem(9, "地铁"), CategoryItem(10, "公交"),
            CategoryItem(11, "打车"), CategoryItem(12, "飞机"),
            CategoryItem(13, "水果"), CategoryItem(14, "零食"),
            CategoryItem(15, "饮料"), CategoryItem(16, "日用品"),
            CategoryItem(17, "衣服"), CategoryItem(18, "鞋子"),
            CategoryItem(19, "包包"), CategoryItem(20, "化妆品"),
            CategoryItem(21, "房租"), CategoryItem(22, "水电"),
            CategoryItem(23, "燃气"), CategoryItem(24, "网费"),
            CategoryItem(25, "话费"), CategoryItem(26, "医疗"),
            CategoryItem(27, "药品"), CategoryItem(28, "运动"),
            CategoryItem(29, "娱乐"), CategoryItem(30, "电影"),
            CategoryItem(31, "游戏"), CategoryItem(32, "书籍"),
            CategoryItem(33, "学习"), CategoryItem(34, "旅游"),
            CategoryItem(35, "其他")
        )

        // 每页显示的数量
        val itemsPerPage = 12
        
        // 计算总页数
        val totalPages = (allSecondaryCategories.size + itemsPerPage - 1) / itemsPerPage

        vpSecondaryCategories.adapter = object : PagerAdapter() {
            override fun getCount(): Int = totalPages

            override fun isViewFromObject(view: View, `object`: Any): Boolean = view == `object`

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                // 计算当前页的数据范围
                val startIndex = position * itemsPerPage
                val endIndex = minOf(startIndex + itemsPerPage, allSecondaryCategories.size)
                val pageCategories = allSecondaryCategories.subList(startIndex, endIndex)
                
                val recyclerView = createRecyclerView(pageCategories)
                container.addView(recyclerView)
                return recyclerView
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(`object` as View)
            }
        }

        val alertDialog = AlertDialog.Builder(this)
            .setTitle("记账")
            .setView(dialogView)
            .setPositiveButton("保存") { dialog, _ ->
                // do nothing here
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                finish()
            }
            .setOnDismissListener {
                finish()
            }
            .show()

        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
            val amount = etMoney.text.toString().toDoubleOrNull() ?: return@setOnClickListener
            val category = primaryCategories[0] // assume the first category is selected
            val note = etNote.text.toString()

            val bill = Bill(
                classify_id = 1, // Replace with actual category ID logic
                second_classify_id = 1, // Replace with actual subcategory ID logic
                money = amount,
                mark = note,
                platform = "widget" // Indicate the source of the record
            )
            CoroutineScope(Dispatchers.IO).launch {
                database.billDao().insert(bill)
            }
            // 发送广播通知小部件刷新
            val intent = Intent("com.apy.accountbook.ACTION_DATA_UPDATED")
            intent.setPackage(packageName)
            sendBroadcast(intent)

            alertDialog.dismiss()
            finish()
        }
    }

    private fun createRecyclerView(categories: List<CategoryItem>): RecyclerView {
        return RecyclerView(this).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutManager = GridLayoutManager(context, 4)
            adapter = SecondaryCategoryAdapter(
                categories = categories,
                getSelectedCategoryId = { selectedSecondaryCategoryId },
                onCategorySelected = { categoryId -> selectedSecondaryCategoryId = categoryId }
            )
        }
    }

    private class SecondaryCategoryAdapter(
        private val categories: List<CategoryItem>,
        private val getSelectedCategoryId: () -> Int?,
        private val onCategorySelected: (Int) -> Unit
    ) : RecyclerView.Adapter<SecondaryCategoryAdapter.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val textView = TextView(parent.context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                setPadding(24, 12, 24, 12)
            }
            return ViewHolder(textView)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val category = categories[position]
            val isSelected = category.id == getSelectedCategoryId()
            holder.bind(category.name, isSelected)
            holder.itemView.setOnClickListener {
                onCategorySelected(category.id)
            }
        }

        override fun getItemCount() = categories.size

        class ViewHolder(private val textView: TextView) : RecyclerView.ViewHolder(textView) {
            fun bind(category: String, isSelected: Boolean) {
                textView.text = category
                if (isSelected) {
                    textView.setTextColor(Color.WHITE)
                    textView.background = ContextCompat.getDrawable(
                        textView.context,
                        R.drawable.bg_category_selected
                    )
                } else {
                    textView.setTextColor(Color.BLACK)
                    textView.background = ContextCompat.getDrawable(
                        textView.context,
                        R.drawable.bg_category_normal
                    )
                }
            }
        }
    }

    private class PrimaryCategoryAdapter(
        private val categories: List<String>,
        private var selectedPosition: Int = 0
    ) : RecyclerView.Adapter<PrimaryCategoryAdapter.ViewHolder>() {

        private var onItemClickListener: ((Int) -> Unit)? = null

        fun setOnItemClickListener(listener: (Int) -> Unit) {
            onItemClickListener = listener
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val textView = TextView(parent.context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                setPadding(24, 12, 24, 12)
            }
            return ViewHolder(textView)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bind(categories[position], position == selectedPosition)
            holder.itemView.setOnClickListener {
                val previousSelected = selectedPosition
                selectedPosition = position
                notifyItemChanged(previousSelected)
                notifyItemChanged(selectedPosition)
                onItemClickListener?.invoke(position)
            }
        }

        override fun getItemCount() = categories.size

        class ViewHolder(private val textView: TextView) : RecyclerView.ViewHolder(textView) {
            fun bind(category: String, isSelected: Boolean) {
                textView.text = category
                if (isSelected) {
                    textView.setTextColor(Color.WHITE)
                    textView.background = ContextCompat.getDrawable(
                        textView.context,
                        R.drawable.bg_category_selected
                    )
                } else {
                    textView.setTextColor(Color.BLACK)
                    textView.background = ContextCompat.getDrawable(
                        textView.context,
                        R.drawable.bg_category_normal
                    )
                }
            }
        }
    }
}